layui.define(['jquery', 'layer','form','element'], function(exports) {
	var $ = layui.jquery,
		layer = layui.layer,
		element = layui.element(),
		form = layui.form(),
		$searchButton = $(".search-button"),
		$toolBtnGroup = $(".tool-btn-box"),
		
		$table=$('.layui-table');
		$tableEditBtn=$table.find('a[xbzx-data-type="edit"]'),
		$tableDeleteBtn=$table.find('a[xbzx-data-type="delete"]'),
		
		$clearBtn = $searchButton.find('button[xbzx-data-type="clear"]'), //清空按钮
		$checkBtn = $searchButton.find('button[xbzx-data-type="check"]'), //检索按钮
		$addBtn = $toolBtnGroup.find('a[xbzx-data-type="add"]'), //增加按钮
		$editBtn = $toolBtnGroup.find('a[xbzx-data-type="edit"]'), //编辑按钮
		$deleteBtn = $toolBtnGroup.find('a[xbzx-data-type="delete"]'), //删除按钮
		$bookBtn = $toolBtnGroup.find('a[xbzx-data-type="bookhandle"]'), //删除按钮
		
		$detailsBtn = $toolBtnGroup.find('a[xbzx-data-type="details"]'), //详情按钮
		$assessmentBtn = $toolBtnGroup.find('a[xbzx-data-type="assessment"]'), //评估按钮
		$dangerBtn = $toolBtnGroup.find('a[xbzx-data-type="danger"]'), //谨慎操作
		addObj='',
		editObj='',
		
		$contextMenu = $('#contextmenu'),
		$docu = $(document);

	var formFn = function(ele, ops, types) {
		//公共参数
		this.$ele = ele,
		$_this = this,
		this.types = types,
		this.defaults = {
			$submitAjax: false,
			$clearBtnFlag: true,
			$checkBtnFlag: true,
			$modal:false
		};
		this.options = $.extend({}, this.defaults, ops)
	};

	formFn.prototype = {
		init: function(addObj,editObj,delObj) {//参数顺序添加，编辑，删除
			var $parEl = $(".xbzx-form");
			switch(this.types) {
				case 'clear':
					this.$clearForm($parEl)
					break;
				case 'check':
					this.$checkForm()
					break;
				case 'add':
					this.$addForm(addObj)
					break;
				case 'edit':
					this.$editForm(editObj)
					break;
				case 'delete':
					this.$deleteForm(delObj)
					break;
				case 'details':
					this.$detailsForm()
					break;
				case 'assessment':
					this.$assessmentForm()
					break;
				case 'danger':
					this.$dangerForm()
					break;
				case 'contextmenu':
					this.$contextmenuForm()
					break;
				default:
					this.$default();
					break;
			}

		},
		$clearForm: function($parEl) {
			if($_this.types === 'clear') {
				if($_this.options.$clearBtnFlag) {
					$parEl.find('input').val("");
					$parEl.find('textarea').val("");
					$parEl.find('select').val("");
					return false;
				} else {
					return false
				}
			}
		},
		$checkForm: function() {
			if($_this.types === 'check') {
				if($_this.options.$checkBtnFlag) {
					if($_this.options.$submitAjax) {
						$('.layui-form').submit();
//						layer.alert('正在提交', {
//							icon: 6,
//							skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
//						})
						return false
					} else {
						return
					}
				} else {
					return false
				}
			} else {
				return false;
			}
		},
		$addForm: function(addObj) {
			//新增按钮所对应的id
			var $addId = addObj.addrel;
			//新增按钮文本
			var $addText = addObj.addtxt;
			//子iframe获取父页面中的元素
			var $windowParentDoc = window.parent.document;
			var $addIframeSrc = addObj.addurl,//新增页面路径
				$headerHeight = $(".layui-header",$windowParentDoc).outerHeight(true), //导航高度
				$mainHeaderHeight = $(".xbzx-cms-cite ul",$windowParentDoc).outerHeight(true), //ul Tab选项卡高度
				$mainHeight = $('.layui-body',$windowParentDoc).height()- $mainHeaderHeight-70, //iframe高度
				$tabContent = $(".layui-tab-content",$windowParentDoc),
				$navHeight =parseFloat($('#admin-side',$windowParentDoc).css('height')); //左边导航栏高度

			//tab-title动态添加li
			var $childIframeTemplate =
				'<li xbzx-data-state="true" lay-id="' + $addId + '" class="layui-this">' +
				'<i class="fa  fa-caret-square-o-right"></i>' +
				'<cite>' + $addText + '</cite>' +
				'<i class="layui-icon layui-unselect layui-tab-close">&#x1006;</i>' +
				'</li>'

				$tabContent.css({
					height: $mainHeight + 30 + 'px',
					minHeight: 150 + 'px'
				});
			
			if($_this.options.$modal){
				layer.open({
		            type: 2,
		            tipsMore: true,
		            content: $editIframeSrc,
		            area:['35%','400px'],
		            title:$editText,
		            maxmin:true,
		            shadeClose: true, //开启遮罩关闭
		            end: function () {
		            	
		            }
		        });
			}else{
			//新增按钮的所对应的iframe
				$iframeTemple = '<div class="layui-tab-item layui-show"><iframe src="' + $addIframeSrc + '" style="height:' + $mainHeight + 'px"></iframe></div>';
	
				var h = $(".layui-tab-title li", $windowParentDoc).last().after($childIframeTemplate);
	
				$(".layui-tab-content div", $windowParentDoc).removeClass("layui-show").last().after($iframeTemple);
				$(".layui-tab-title li[lay-id=" + $addId + "]", $windowParentDoc).last().addClass('layui-this').siblings().removeClass('layui-this')
				$(".xbzx_left_menu dd", $windowParentDoc).removeClass('layui-this');
				$(".layui-side ul li", $windowParentDoc).removeClass('layui-this');
	
				$(".layui-tab-title li[lay-id=" + $addId + "]", $windowParentDoc).off('mousedown').on('mousedown','i.layui-tab-close',function(){
					var $index = $(this).parent('li').index();
					var len = $(".layui-tab-title li",$windowParentDoc).length - 1;
	
					//点击关闭无高亮显示的新增时候进行判断
					if($(".layui-tab-title li",$windowParentDoc).eq($index).hasClass('layui-this')){
	
						$(".layui-tab-title li", $windowParentDoc).eq($index).remove();
						$(".layui-tab-content div", $windowParentDoc).eq($index).remove();
	
						if($index == len){
								$(".layui-tab-title li",$windowParentDoc).eq($index-1).addClass('layui-this');
								$(".layui-tab-content div",$windowParentDoc).eq($index-1).addClass('layui-show');
						}
	
						if($index < len){
							$(".layui-tab-title li",$windowParentDoc).eq($index).addClass('layui-this');
							$(".layui-tab-content div",$windowParentDoc).eq($index).addClass('layui-show');
						}
					}else {
						$(".layui-tab-title li", $windowParentDoc).eq($index).remove();
						$(".layui-tab-content div", $windowParentDoc).eq($index).remove();
					}
					//这个功能是干啥的我暂时忘了....
					parent.layui.element().init();
					var $cId = $(".layui-tab-title li.layui-this",$windowParentDoc).attr('lay-id');
					$('.xbzx_left_menu li',$windowParentDoc).removeClass('layui-nav-itemed')
						$('.xbzx_left_menu li a[data-id="'+ $cId +'"]',$windowParentDoc).parent().addClass('layui-nav-itemed')
					});
					
				}
		},
		$editForm: function(editObj) {
			//新增按钮所对应的id
			var $editId = editObj.editrel;
			var $cachId = editObj.$editCachId
			//新增按钮文本
			var $editText = editObj.edittxt;
			//子iframe获取父页面中的元素
			var $windowParentDoc = window.parent.document;
			//新增页面路径
			var $editIframeSrc =editObj.editurl,
				$headerHeight = $(".layui-header",$windowParentDoc).outerHeight(true), //导航高度
				$mainHeaderHeight = $(".xbzx-cms-cite ul",$windowParentDoc).outerHeight(true), //ul Tab选项卡高度
				$mainHeight = $('.layui-body',$windowParentDoc).height()- $mainHeaderHeight-70, //iframe高度
				$tabContent = $(".layui-tab-content",$windowParentDoc),
				$navHeight =parseFloat($('#admin-side',$windowParentDoc).css('height')); //左边导航栏高度

			//tab-title动态添加li
			var $childIframeTemplate =
				'<li xbzx-data-state="true" lay-id="' + $editId + '" class="layui-this">' +
				'<i class="fa  fa-caret-square-o-right"></i>' +
				'<cite data-len="6">' + $editText + '</cite>' +
				'<i class="layui-icon layui-unselect layui-tab-close">&#x1006;</i>' +
				'</li>';

				$tabContent.css({
					height: $mainHeight + 30 + 'px',
					minHeight: 150 + 'px'
				});
				
				if($_this.options.$modal){
					layer.open({
			            type: 2,
			            tipsMore: true,
			            content: $editIframeSrc,
			            area:['35%','400px'],
			            title:$editText,
			            maxmin:true,
			            shadeClose: true, //开启遮罩关闭
			            end: function () {
			            	
			            }
			        });
				}else{

					var $relTab=$('.layui-tab-title li[lay-id="'+$editId+'"]',$windowParentDoc);
					var $ii = $relTab.index()-1,
						$iiLayId = $('#xbzx-cms-tab .layui-tab-title li',$windowParentDoc).eq($ii).attr("lay-id");
					console.log($iiLayId)
					if($relTab.length !== 0) {
						var $i=$relTab.index()+1;
						// 如果页面有iframe 则要判断id
						var src = $('.layui-tab-content div:nth-child('+$i+') iframe',$windowParentDoc).attr('src');
						if(src.indexOf('id') > 0) {
							var hasId = src.substring(src.indexOf('id') + 3, src.length)
						}
						if(hasId === $cachId) {
							$('.layui-tab-title li:nth-child('+$i+')',$windowParentDoc).addClass('layui-this').siblings('.layui-this').removeClass('layui-this');
							$('.layui-tab-content div:nth-child('+$i+')',$windowParentDoc).addClass('layui-show').siblings('.layui-show').removeClass('layui-show');
//							parent.layui.element().tabChange('xbzx-cms-tab', $editId);
						} else {
							$iframeTemple = '<div class="layui-tab-item layui-show"><iframe src="' + $editIframeSrc + '" style="height:' + $mainHeight + 'px"></iframe></div>';
							parent.layui.element().tabDelete('xbzx-cms-tab', $editId);
							parent.layui.element().tabAdd('xbzx-cms-tab', {
								title: $editText,
								content: $iframeTemple, //支持传入html
								id: $editId,
								xbTp: $editId,
								icon: 'fa fa-caret-square-o-right',
								dataLen: 6
							});
							parent.layui.element().tabChange('xbzx-cms-tab', $editId);
							parent.layui.element().init();
						}
					} else {
						//新增按钮的所对应的iframe
						$iframeTemple = '<div class="layui-tab-item layui-show"><iframe src="' + $editIframeSrc + '" style="height:' + $mainHeight + 'px"></iframe></div>';
						var h = $(".layui-tab-title li", $windowParentDoc).last().after($childIframeTemplate);
			
						$(".layui-tab-content div", $windowParentDoc).removeClass("layui-show").last().after($iframeTemple);
						$(".layui-tab-title li[lay-id=" + $editId + "]", $windowParentDoc).last().addClass('layui-this').siblings().removeClass('layui-this')
						$(".xbzx_left_menu dd", $windowParentDoc).removeClass('layui-this');
						$(".layui-side ul li", $windowParentDoc).removeClass('layui-this');
			
						$(".layui-tab-title li[lay-id=" + $editId + "]", $windowParentDoc).off('mousedown').on('mousedown','i.layui-tab-close',function(){
							var $index = $(this).parent('li').index();
							var len = $(".layui-tab-title li",$windowParentDoc).length - 1;
			
							//点击关闭无高亮显示的新增时候进行判断
							if($(".layui-tab-title li",$windowParentDoc).eq($index).hasClass('layui-this')){
			
								$(".layui-tab-title li", $windowParentDoc).eq($index).remove();
								$(".layui-tab-content div", $windowParentDoc).eq($index).remove();
			
								if($index == len){
										$(".layui-tab-title li",$windowParentDoc).eq($index-1).addClass('layui-this');
										$(".layui-tab-content div",$windowParentDoc).eq($index-1).addClass('layui-show');
								}
			
								if($index < len){
									$(".layui-tab-title li",$windowParentDoc).eq($index).addClass('layui-this');
									$(".layui-tab-content div",$windowParentDoc).eq($index).addClass('layui-show');
								}
							}else {
								$(".layui-tab-title li", $windowParentDoc).eq($index).remove();
								$(".layui-tab-content div", $windowParentDoc).eq($index).remove();
							}
							//这个功能是干啥的我暂时忘了....
							})
					}
					var $cId = $(".layui-tab-title li.layui-this",$windowParentDoc).attr('lay-id');
					$('.xbzx_left_menu li',$windowParentDoc).removeClass('layui-nav-itemed')
						$('.xbzx_left_menu li a[data-id="'+ $cId +'"]',$windowParentDoc).parent().addClass('layui-nav-itemed')
				}
		},
		$deleteForm: function(delObj) {
			var delTxt=delObj.deltxt;
			var delUrl=delObj.delurl;
			var a = {};
			
			layer.confirm( delTxt, {
			  btn: ['是的','取消'] //按钮
			}, function(){
				var dataParass='{"maxnum":'+3+',"minnum":0}';
				$.ajax({
					type:"POST",
					url:delUrl,
					data:dataParass,
					success:function (data) {
						console.log(data);
						var loadRel=data.url;
						if(data.code==200){
							parent.parent.layer.msg(data.msg, {time: 3000, icon:6});
						}
						else{
							parent.parent.layer.msg(data.msg, {time: 3000, icon:2});
						}
						$('iframe[id="iNow"]',window.parent.parent.document).each(function(i){
						   if($(this).attr('data-rel') === loadRel){
							  var ifName = $(this).attr('name');
							  window.parent.frames[ifName].location.reload(true);
						   }
						})
					}
				})
			}, function(){
			  layer.msg('取消中...', {time: 400 });
			});

		},
		$detailsForm: function() {
			alert('$detailsForm')
		},
		$assessmentForm: function() {
			alert('$assessmentForm')
		},
		$dangerForm: function() {
			alert('$dangerForm')
		},
		$contextmenuForm: function() {
			if($("#contextmenu", window.parent.document).length >= 1) {
				$("#contextmenu", window.parent.document).remove()
			}
			return false
		},
		$default: function() {
			layer.alert('是不是types没写？或者写错了？', {
				skin: 'layui-layer-molv',
				closeBtn: 0,
				anim: 1 //动画类型
			});

		}
	};
	
	var chktrDom='',trLen='',trId='';
	function findCheckOne(){
		chktrDom=$('.layui-table tr.checkOne');
		trLen=chktrDom.length;
		trId=chktrDom.attr('data-id');
	}

   /*点击tr选择对应input  */
	$('.layui-table tbody>tr').click(function(e){
		$(this).addClass('checkOne').siblings('.checkOne').removeClass('checkOne');
	});
   
   
	$clearBtn.on('click', function(e) {
		e.preventDefault();
		var $clear = new formFn($clearBtn, {}, 'clear');
		$clear.init();
		return false
	});

	$checkBtn.on('click', function(e) {
		e.preventDefault();
		var $submintAjax = true;
		var $check = new formFn($checkBtn, {
			$submitAjax: $submintAjax
		}, 'check')
		$check.init();
		if($submintAjax) {
			return false;
		} else {
			return
		}
	});

	$addBtn.on("click", function(e) {
		e.preventDefault();
		
		var $windowParentDoc = window.parent.document;
		var addUrl=$(this).attr('data-url');
		var addRel=$(this).attr('data-rel');
		var addTxt=$(this).attr('tab-title');
		    addObj={addurl:addUrl,addrel:addRel,addtxt:addTxt}
		
		var $relTab=$('.layui-tab-title li[lay-id="'+addRel+'"]',$windowParentDoc);
		if($relTab.length!==0){
			var $i=$relTab.index()+1;
			$('.layui-tab-title li:nth-child('+$i+')',$windowParentDoc).addClass('layui-this').siblings('.layui-this').removeClass('layui-this');
			$('.layui-tab-content div:nth-child('+$i+')',$windowParentDoc).addClass('layui-show').siblings('.layui-show').removeClass('layui-show');
			window.location.reload()
		}else{
			var $add = new formFn($add, {$modal: false}, 'add');
			$add.init(addObj);
			return false;
		}
	});
	
	var $editCachId = '';
	$editBtn.add($tableEditBtn).on("click", function(e) {
		e.preventDefault();
		var that=$(this);
		function openEdit(trID){
			var $windowParentDoc = window.parent.document;
			var $editCachId=trID;
			var isModal=that.attr('data-modal');
			
			var editUrl=that.attr('data-url')+'?id='+trId;
			var editRel=that.attr('data-rel');
			var editTxt=that.attr('tab-title');
			   editObj={editurl:editUrl,editrel:editRel,edittxt:editTxt,$editCachId:$editCachId}
			
			var $relTab=$('.layui-tab-title li[lay-id="'+editRel+'"]',$windowParentDoc);
			if($relTab.length!==0){	
				var $edit = new formFn($edit, {$modal: isModal}, 'edit');
				$edit.init(addObj,editObj);
				layui.element().init();
			}else{
				var $edit = new formFn($edit, {$modal: isModal}, 'edit');
				$edit.init(addObj,editObj);
				parent.layui.element().init();
			}
		}
		
		if($(this).attr('data-id')){
			var trId=$(this).attr('data-id');
			openEdit(trId);
		}else{
			findCheckOne();
			var type = $(this).attr("data-rel");
			
			if(trLen==0){
				if(type === "sys_detail") {
					layer.msg('请至少选择一项查看');
				} else {
					layer.msg('请至少选择一项修改');
				}
			}else{
				var trId=chktrDom.attr('data-id');
				openEdit(trId);
			}
		}
		
	});

	$deleteBtn.add($tableDeleteBtn).on('click',function () {
		var that=$(this);
		if($(this).attr('data-id')){
			var trId=$(this).attr('data-id');
			opendelete(trId);
		}else{
			findCheckOne();
		    if(trLen==0){
		    	layer.msg('请至少选择一项删除');
			}else{
				var trId=chktrDom.attr('data-id');
			    opendelete(trId);
			}
		}
	    
	    function opendelete(trID){
	    	var delUrl=that.attr('data-url')+'?id='+trID;
			var delRel=that.attr('data-rel');
			var delTxt=that.attr('tab-title');
			var delObj={delurl:delUrl,delrel:delRel,deltxt:delTxt}
			    
			var $delete = new formFn($delete, {}, 'delete');
			$delete.init(addObj,editObj,delObj);
			return false;
	    }
	});
	
	$bookBtn.on('click',function (e) {
		e.preventDefault();
		findCheckOne();
		var btnTxt=$(this).attr('tab-title');
		if(trLen==0){
			layer.msg('请至少选择一项'+btnTxt);
		}else if(trLen==1){
			var trId=chktrDom.attr('data-id');
			var $titleTxt=$(this).attr('tab-title');
			var requUrl=$(this).attr('data-requesturl');
			
			$.ajax({
		    	 type: 'POST',
				  url: requUrl+'?id='+trId,
				  success:function(data){
					  console.log(data)
					  if(data.code==300){
						  layer.msg(data.msg, {time: 3000, icon:6})
					  }else if(data.code==200){
						  var pageUrl=data.url;
						  layer.open({
					            type: 2,
					            tipsMore: true,
					            content:pageUrl+'?id='+trId,
					            area:['50%','600px'],
					            title:$titleTxt,
					            maxmin:true,
					            shadeClose: true, //开启遮罩关闭
					            end: function () {
					            	
					            }
					        });
						  return;
					  }
				  },
				  error:function(){
					  layer.msg("请求失败", {time: 300});
				  }
		    });
			
		}
	});
	
	$docu.on("click", function() {
			var $contextMenu = new formFn($docu, {}, 'contextmenu');
			$contextMenu.init();
			return false;
	});
	//阻止body中的事件冒泡和其他layui中给body添加的默认行为
	$(document.body).off("click").on('click',function(e){
		if($("#contextmenu", window.parent.document).length >= 1){
			var $contextMenu = new formFn($docu, {}, 'contextmenu');
			$contextMenu.init();
			return false;
		}

		if($(".layui-select-title").find('input[type="text"]').val() == "") {
			window.event? window.event.cancelBubble = true : e.stopPropagation();
		}
	});
	
	exports('xbzx-cms-common', {}); //注意，这里是模块输出的核心，模块名必须和use时的模块名一致
});
